package edu.ntnu.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import edu.wsu.KheperaSimulator.RobotController;

/*
 * This class makes the strategy of robot's behavior.
 * Decides the order of states.
 */
public class Strategy {

	private RobotController robot;
	private State state;
	private List<Class<? extends State>> tasks;
	Iterator<Class<? extends State>> task;

	public Strategy(RobotController newRobot) {

		// clear map for new maze
		MapBuilder.getNewInstance();
		
		// strategy
		tasks = new ArrayList<Class<? extends State>>();
		tasks.add(Explore.class);
		tasks.add(Collect.class);
		tasks.add(Finished.class);
		task = tasks.iterator();
		
		robot = newRobot;
		try {
			state = task.next().getConstructor(RobotController.class).newInstance(robot);
		} catch (Exception e) {
			System.err.println("Exception during creating new instance: " + e + "\n");
			state = new Finished(robot);
		}
	}
	
	public void doAction() {
		if(state.doAction()) {
			try {
				state = task.next().getConstructor(RobotController.class).newInstance(robot);
			} catch (InvocationTargetException ite) {
				System.err.println("Light was not found");
				state = new Finished(robot);
			} catch (Exception e) {
				System.err.println("Exception during creating new instance: " + e + "\n");
				state = new Finished(robot);
			}
		}
	}
}

